package MyQueue;

public class MyQueue implements Operations{

    public ListNode headNode;//头结点

    public ListNode lastNode;//尾结点

    public int usedSize;

    public MyQueue() {
        this.headNode = null;
        this.lastNode = null;
    }

    //双向尾插
    @Override
    public boolean offer(int data) {
        ListNode newNode = new ListNode(data);

        if (isEmpty()) {
            this.headNode = newNode;
            this.lastNode = newNode;
            this.usedSize++;
            return true;
        }
        newNode.prevNode = this.lastNode;
        this.lastNode.nextNode = newNode;
        this.lastNode = newNode;
        this.usedSize++;

        return true;
    }

    //双向链表头删
    @Override
    public int poll() {
        if (isEmpty()) {
            throw new EmptyQueueException("空队列，无法出队列");
        }

        int val = this.headNode.val;
        if (this.headNode == this.lastNode) {
            this.headNode = null;
            this.lastNode = null;
        } else {
            this.headNode = this.headNode.nextNode;
            this.headNode.prevNode = null;
        }
        this.usedSize--;
        return val;
    }

    //取头结点值
    @Override
    public int peek() {
        if (isEmpty()) {
            throw new EmptyQueueException("空队列，无法出队列");
        }

        int val = this.headNode.val;
        return val;
    }

    @Override
    public int size() {
        return this.usedSize;
    }

    @Override
    public boolean isEmpty() {
        return this.usedSize == 0;
    }
}
